package admin

import (
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/gtime"
	"duoke/utils/orm"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
	"github.com/syyongx/php2go"
	"strings"
)

var Screenboard = new(screenboardCtl)

type screenboardCtl struct{}

// 商品信息
func (ctl *screenboardCtl) Goods(c *gin.Context) {
	goodsR, _ := service.Request.Goods(c)
	response.Success(c, "", goodsR)
}

// 今日数据趋势
func (ctl *screenboardCtl) Line(c *gin.Context) {
	goodsR, _ := service.Request.Goods(c)
	today, _ := gtime.TodayStamp()
	today0 := gconv.Int(today)
	var uv [7]int64
	var pv [7]int64
	var user [7]int64
	var order [7]int64
	behavior := new(tables.Behavior)
	order2 := new(tables.Order)
	goodsUser := new(tables.GoodsUser)
	for i := 0; i <= 6; i++ {
		if i == 0 {
			uv[i] = 0
		} else {
			uv[i], _ = orm.Db.Where("goods_id =? AND created_at between ? and ?", goodsR.Id, today0+(14400*(i-1)), today0+(14400*i)).Distinct("user_id").Count(behavior)
		}
		if i == 0 {
			pv[i] = 0
		} else {
			pv[i], _ = orm.Db.Where("goods_id =? AND created_at between ? and ?", goodsR.Id, today0+(14400*(i-1)), today0+(14400*i)).Count(behavior)
		}
		if i == 0 {
			user[i] = 0
		} else {
			user[i], _ = orm.Db.Where("goods_id =? AND created_at between ? and ?", goodsR.Id, today0+(14400*(i-1)), today0+(14400*i)).Count(goodsUser)
		}
		if i == 0 {
			order[i] = 0
		} else {
			order[i], _ = orm.Db.Where("goods_id =? AND is_robot=0 AND pay_state=1 AND pay_time between ? and ?", goodsR.Id, today0+(14400*(i-1)), today0+(14400*i)).MustLogSQL().Count(order2)
		}

	}
	data := []gin.H{
		{
			"name":  "UV",
			"type":  "line",
			"stack": "Total",
			"data":  uv,
		},
		{
			"name":  "PV",
			"type":  "line",
			"stack": "Total",
			"data":  pv,
		},
		{
			"name":  "用户",
			"type":  "line",
			"stack": "Total",
			"data":  user,
		},
		{
			"name":  "订单",
			"type":  "line",
			"stack": "Total",
			"data":  order,
		},
	}
	response.Success(c, "", data)
}

// 订单实时数据
func (ctl *screenboardCtl) Time(c *gin.Context) {
	goodsR, _ := service.Request.Goods(c)
	today_start, todat_end := gtime.TodayStamp()
	// 最新订单
	newOrder := make([]model.ScreenNewOrder, 0)
	err := orm.Db.Where("goods_id =? AND is_robot=0 AND pay_state=1", goodsR.Id).Limit(100).Desc("id").Find(&newOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	for i, v := range newOrder {
		if v.HeadUserId != 0 && v.HeadUserId != v.UserId {
			newOrder[i].HeadNickname = service.User.GetValueById(v.HeadUserId, "nickname")
		} else {
			newOrder[i].HeadNickname = "团长"
		}
		newOrder[i].FromUser = service.GoodsUser.GetById(c, goodsR.Id, v.FromId, "nickname,avatar")
		newOrder[i].Staff = service.GoodsUser.GetById(c, goodsR.Id, v.StaffId, "nickname,avatar")
		newOrder[i].MemberNum = v.GroupMemberNum
		newOrder[i].OrderTime = php2go.Date("15:04:05", gconv.Int64(v.PayTime))
	}
	// 30分钟内正在报名用户
	doingOrder := make([]model.ScreenNewOrder, 0)
	err = orm.Db.Where("goods_id =? AND is_robot=0 AND pay_state=0 AND created_at >?", goodsR.Id, php2go.Time()-3600).Limit(100).Desc("id").Find(&doingOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	for i, v := range doingOrder {
		if v.HeadUserId != 0 && v.HeadUserId != v.UserId {
			doingOrder[i].HeadNickname = service.User.GetValueById(v.HeadUserId, "nickname")
		} else {
			doingOrder[i].HeadNickname = "团长"
		}
		doingOrder[i].FromUser = service.GoodsUser.GetById(c, goodsR.Id, v.FromId, "nickname,avatar")
		doingOrder[i].Staff = service.GoodsUser.GetById(c, goodsR.Id, v.StaffId, "nickname,avatar")
		doingOrder[i].MemberNum = v.GroupMemberNum
		doingOrder[i].OrderTime = php2go.Date("15:04:05", gconv.Int64(v.PayTime))
	}
	// 员工排行
	staffRanking := make([]model.ScreenStaff, 0)
	err = orm.Db.Where("goods_id =? AND is_staff = 1", goodsR.Id).Find(&staffRanking)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	for i, v := range staffRanking {
		staffRanking[i].OrderNum, _ = orm.Db.Where("goods_id =? AND (staff_id =? OR from_id =?) AND is_robot = 0 AND pay_state = 1", goodsR.Id, v.UserId, v.UserId).Count(tables.Order{})
		staffRanking[i].InviteNum, _ = orm.Db.Where("goods_id =? AND (staff_id =? OR from_id =?)", goodsR.Id, v.UserId, v.UserId).Count(tables.GoodsUser{})
		staffRanking[i].ShareNum, _ = orm.Db.Where("goods_id =? AND user_id =? AND (action = 'share_app_message' OR action = 'share_timeline')", goodsR.Id, v.UserId).Sum(new(tables.Behavior), "num")
	}
	// 意向客户
	intendedCustomers := make([]model.ScreenNewOrder, 0)
	err = orm.Db.Where("goods_id =? AND is_robot=0 AND pay_state=0", goodsR.Id).Limit(100).Desc("id").Find(&intendedCustomers)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 商品用户数
	countGoodsUser, _ := orm.Db.Where("goods_id =?", goodsR.Id).Count(tables.GoodsUser{})
	// 商品员工数
	countGoodsStaff, _ := orm.Db.Where("goods_id =? AND is_staff = 1", goodsR.Id).Count(tables.GoodsUser{})
	// 今日团数量
	todayGroupNum, _ := orm.Db.Where("goods_id =? AND is_robot = 0 AND pay_state = 1 AND is_head = 1 AND pay_time between ? and ?", goodsR.Id, today_start, todat_end).Count(tables.Order{})
	// 所有团数量
	groupNum, _ := orm.Db.Where("goods_id =? AND is_robot = 0 AND pay_state = 1 AND is_head = 1", goodsR.Id).Count(tables.Order{})
	// 分享数量
	shareNum, _ := orm.Db.Where("goods_id =? AND (action = 'share_app_message' OR action = 'share_timeline')", goodsR.Id).Count(tables.Behavior{})
	// 最后订单号
	var lastOrder interface{}
	if len(newOrder) > 0 {
		lastOrder = newOrder[0]
	} else {
		lastOrder = nil
	}
	data := gin.H{
		"uv":                 countGoodsUser,
		"pv":                 goodsR.Views,
		"staff_num":          countGoodsStaff,
		"success_order_num":  strings.Split(gconv.String(goodsR.Sales), ""),
		"today_group_num":    todayGroupNum,
		"group_num":          groupNum,
		"order_num":          goodsR.Sales,
		"income":             goodsR.Income,
		"today_order":        newOrder,
		"today_doing":        doingOrder,
		"share_num":          shareNum,
		"stock":              goodsR.Stock,
		"staff_ranking":      staffRanking,
		"intended_customers": intendedCustomers,
		"last_order":         lastOrder,
	}
	response.Success(c, "", data)
}

// 订单实时数据
func (ctl *screenboardCtl) Order(c *gin.Context) {
	goodsR, _ := service.Request.Goods(c)
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 分页
	offset := (req.PageNo - 1) * req.PageSize
	orderList := make([]model.ScreenNewOrder, 0)
	order := orm.Db.Where("goods_id =? AND is_robot=0 AND pay_state=1", goodsR.Id).Limit(req.PageSize, offset).Desc("id")
	if req.GroupNum != "" {
		order = order.Where("group_num =?", req.GroupNum)
	}
	if req.GroupMemberNum != "" {
		order = order.Where("group_member_num =?", req.GroupMemberNum)
	}
	total, err := order.FindAndCount(&orderList)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	for i, v := range orderList {
		orderList[i].Staff = service.GoodsUser.GetById(c, goodsR.Id, v.StaffId, "nickname,avatar")
		orderList[i].Head = service.GoodsUser.GetById(c, goodsR.Id, v.HeadUserId, "nickname,avatar")
		if v.GroupId > 0 {
			member, err := service.Group.Member(req, v.GroupId, true, "")
			if err != nil {
				response.Error(c, err.Error(), nil)
				return
			}
			orderList[i].Member = member
		} else {
			orderList[i].Member = nil
		}
	}
	response.Success(c, "", gin.H{"total": total, "list": orderList})
}

// 用户行为
func (ctl *screenboardCtl) Behavior(c *gin.Context) {
	goodsR, _ := service.Request.Goods(c)
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if req.UserId == 0 {
		response.Error(c, "用户ID不存在", nil)
		return
	}
	user := service.GoodsUser.GetById(c, goodsR.Id, req.UserId, "user_id,nickname,avatar")
	// 行为
	log := make([]tables.Behavior, 0)
	err := orm.Db.Where("goods_id =? AND user_id=?", goodsR.Id, user.UserId).Desc("id").Find(&log)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 总浏览数
	totalViewNum, _ := orm.Db.Where("goods_id =? AND user_id=? AND action=?", goodsR.Id, user.UserId, "view").Count(new(tables.Behavior))
	//总浏览时间
	totalViewTime, _ := orm.Db.Where("goods_id =? AND user_id=? AND action=?", goodsR.Id, user.UserId, "view").Sum(new(tables.Behavior), "view_time")
	//分享好友次数
	totalShareAppNum, _ := orm.Db.Where("goods_id =? AND user_id=? AND action=?", goodsR.Id, user.UserId, "share_app_message").Count(new(tables.Behavior))
	//分享朋友圈次数
	totalShareLineNum, _ := orm.Db.Where("goods_id =? AND user_id=? AND action=?", goodsR.Id, user.UserId, "share_timeline").Count(new(tables.Behavior))
	//浏览完整度
	behavior := new(tables.Behavior)
	_, _ = orm.Db.Where("goods_id =? AND user_id=? AND action=?", goodsR.Id, user.UserId, "view").Desc("view_percentage").Get(behavior)
	data := gin.H{
		"log":                  log,
		"total_view_num":       totalViewNum,
		"total_view_time":      totalViewTime,
		"total_share_app_num":  totalShareAppNum,
		"total_share_line_num": totalShareLineNum,
		"max_view_percentage":  behavior.ViewPercentage,
		"user":                 user,
	}
	response.Success(c, "", data)
}
